import Vue from 'vue'
import App from './App'
import router from './router'
import Print from 'vue-print-nb'
import moment from 'moment'
import {Message, Loading } from 'element-ui';
import pinyin from 'js-pinyin'
// 图片缩放
import preview from 'vue-photo-preview'
import 'vue-photo-preview/dist/skin.css'
/*---------------- New ----------------*/
import axios from 'axios'
//防止重复点击
import preventReClick from './utils/preventReClick'
Vue.prototype.$http = axios;
import { ajax } from '@/api/axios'
Vue.prototype.ajax = ajax;
/* let instance = axios.create({
  baseURL: '',
  timeout: 60000
}) */
// 请求超时时间
axios.defaults.timeout = 30000
// 当页面有两个接口时，第一个接口loading的close事件会直接将第二个接口的loading实例也close
let loadingInstance = null; // 定义loading变量
function startLoading () {
  loadingInstance = Loading.service({
    fullscreen: true,
    text: '拼命加载中...',
    background: 'rgba(0, 0, 0, 1)'
  })
}
function endLoading () { // 使用Element loading-close 方法
  loadingInstance.close();
}
// 那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事儿就是将同一时刻的请求合并。
// 声明一个变量 needLoadingRequestCount，每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
// 调用tryHideFullScreenLoading()方法，needLoadingRequestCount - 1。needLoadingRequestCount为 0 时，结束 loading。
let needLoadingRequestCount = 0;
function showFullScreenLoading () {
  if (needLoadingRequestCount === 0) {
    startLoading();
  }
  needLoadingRequestCount++;
}
function tryHideFullScreenLoading () {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--;
  if (needLoadingRequestCount === 0) {
    endLoading();
  }
}
// 请求拦截
axios.interceptors.request.use(config => {
  // get请求添加随机字符串
  if (config.method === 'get') {
    const urlStr = {
      [true]: '&t=' + Date.now(),
      [false]: '?t=' + Date.now()
    };
    config.url = config.url + urlStr[config.url.includes('?')];
  }
  if(config.config){ // 原来用ajax请求数据的只有一层config
    if(config.config.showFullScreenLoading === true) {
      showFullScreenLoading();
    }
  }
  return config;
}, error => {
  tryHideFullScreenLoading();
  Message.error({message: '请求超时!'});
  return Promise.reject(error);
})
// 响应拦截
axios.interceptors.response.use(
  response => {
    tryHideFullScreenLoading(); // 响应成功关闭loading
    let res = response.data;
    if (response.data.code === '200') {
      return response;
    } else if (res.type) { // 文件导出
      return response;
    } else {
      Vue.prototype.$message({ message: res.message, type: 'error' });
      startLoading();
      loadingInstance.close();
    }
  }, error => {
    tryHideFullScreenLoading();
    Vue.prototype.$message({ message: '服务器链接失败', type: 'error' });
    return Promise.reject(error);
  })
Vue.prototype.$axios = axios;

import store from './store/index'

import iView from 'iview'
import 'iview/dist/styles/iview.css'

Vue.use(iView);

import echarts from 'echarts'

Vue.prototype.$echarts = echarts;
Vue.prototype.$moment = moment;

// import md5 from 'js-md5'

import api from './api/index'

Vue.prototype.api = api;

import commonConst from './utils/commonConst'

Vue.prototype.commonConst = commonConst;

import commonFunction from './utils/commonFunction'

Vue.prototype.commonFunction = commonFunction;
Vue.prototype.pinyin=pinyin

Vue.config.productionTip = false;

Vue.prototype.post = function (url, param, config = { showFullScreenLoading: false } ) {
  if (!param) {
    param = {};
  }
  param.loginId = JSON.parse(sessionStorage.getItem('id'));
  param.token = JSON.parse(sessionStorage.getItem('token'));
  param.client = "manager";
  // return this.$http.post(url, param, config);
  return new Promise((resolve, reject) => {
    axios ({
      method: 'post',
      url: url,
      data: param,
      config: config
    }).then(response => {
      // 请求成功
      resolve(response)
    }).catch(err => {
      // 请求失败
      console.log('请求失败');
      reject(err)
    })
  })
};

Vue.use(preview);
router.beforeEach((to, from, next) => {
  if (to.name != 'login') {
    let isLogin = sessionStorage.getItem('token')
    if (isLogin) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})
/* router.beforeEach((to, from, next) => {
  console.log(to)
  // 需求登录判断
  if (to.path != '/login') {
    // 未登录
    var isLogin = sessionStorage.getItem('token')
    if (isLogin) {
      let list = JSON.parse(localStorage.getItem('menu')) || []
      let canReview = []
      if (list.length) {
        for (let i = 0; i < list.length; i++) {
          const element = list[i];
          if (element.children) {
            for (let j = 0; j < element.children.length; j++) {
              const ele = element.children[j];
              canReview.push(ele.href)
            }
          }
        }
        console.log(canReview.includes(to.name))
        if (canReview.includes(to.name)) {
          next()
        } else {
          next('/login')
        }
      } else {
        next()
      }
    } else {
      next('/login')
    }
  } else {
    next()
  }
}) */

// 跳转后返回顶部
router.afterEach((to, from, next) => {
  window.scrollTo(0, 0);
})
/*Element-UI*/
import ElementUI from 'element-ui';
import './theme/index.css';
// import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI, { size: 'small', zIndex: 3000 });
Vue.use(Print);
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>',
  render: h => h(App)
});

/*easyTable*/
import 'vue-easytable/libs/themes-base/index.css'
import { VTable, VPagination } from 'vue-easytable'
Vue.component(VTable.name, VTable)
Vue.component(VPagination.name, VPagination)

/*vue-infinite-loading*/
import InfiniteLoading from 'vue-infinite-loading';
Vue.use(InfiniteLoading, {
  slots: {
    noMore: '没有更多数据了',
    noResults: ''
  },
});
